declare var wx: any;
import { JsonAsset, sys, TiledTile, view } from "cc";
import UrlEnum from "../Res/UrlEnum";
import Http, { IHttpMethod } from "../Net/Http";
import SdkInterface from "./SdkInterface";
import SdkTool from "./SdkTool";
import { ViewManager } from "../../Game/module/base/ViewManager";
import { SocketManager } from "../../Game/module/socket/SocketManager";
import ProtoBufManager from "../../Game/proto/ProtoBufManager";
import { http } from "../../Game/proto/protoCmd";
import EventMgr from "../Event/EventMgr";
import { GameModels } from "../../Game/module/socket/GameModels";
import Log from "../Log/Log";
export default class WxSdk implements SdkInterface {

    private videoAd: any;
    private callback: any;
    private target: any;
    private bannerAd: any;
    private interstitialAd: any;
    private customAd: any;
    /**
     * 初始化
     * @param callback 初始化成功后回调
     * @param target 监听对象
     */
    public init(callback: Function, target: Object): void {
        Log.ins.log(1, "WxSdk init");
        this.createRewardAd();
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
        wx.onShareAppMessage(() => {
            return {
                // title: '',
                // imageUrlId: ``,
                // imageUrl: ``
            }
        })
        wx.onShow(this.onshow.bind(this));
        SdkTool.ins.sidebar = false;
        SdkTool.ins.isSidebar = false;
    }
    private onshow(res): void {
        Log.ins.log(1, `onShow`, res.query);
        SdkTool.ins.query[`roomid`] = res.query.roomid;
        SdkTool.ins.query[`nickname`] = res.query.nickname;
        EventMgr.emit(`yaoqingrenroom`);
    }
    /**
     * 登录
     * @param callback 登录成功后回调
     * @param target 监听对象
     */
    public login(): void {
        Log.ins.log(1, "WxSdk login");
        this.wxLoginCode();
    }
    /**游戏服登录 */
    private loginGameServer(code): void {
        const reqData = ProtoBufManager.ins.http.ReqEntry.create();
        reqData.Token = code;
        reqData.ChannelId = ProtoBufManager.ins.common.EChannelId.WX;
        const data: Uint8Array = ProtoBufManager.ins.http.ReqEntry.encode(reqData).finish();
        Http.ins.request(`${UrlEnum.httpUrl}entry`, data.slice().buffer, (data) => {
            if (!data) {
                EventMgr.emit(`serverError`);
                return;
            }
            ViewManager.ins.removeLoading();
            const rawData = new Uint8Array(data);
            const buf: http.RespEntry = ProtoBufManager.ins.http.RespEntry.decode(rawData);
            if (buf.ErrCode != ProtoBufManager.ins.common.ErrorCode.OK) {
                Log.ins.log(4, `登录游戏服失败,错误码:${buf.ErrCode}`);
                EventMgr.emit(`wxLogin`, false);
                return;
            }
            if (!buf.WSUrl.Host) {
                EventMgr.emit(`serverError`);
                return;
            }
            UrlEnum.socketip = `${buf.WSUrl.Host}:${buf.WSUrl.Port}`;
            Log.ins.log(2, `登录游戏服成功,玩家uid:${buf.UId}`);
            Log.ins.log(2, `游戏大厅路由:${buf.LobbyRoute}`);
            Log.ins.log(2, `游戏服地址:${UrlEnum.socketip}`);
            Log.ins.log(2, `${buf.IsNewAccount ? "是新用户" : "是老用户"}`);
            SdkTool.ins.isFirst = buf.IsNewAccount;
            GameModels.info.playerInfo.UserId = buf.UId;
            GameModels.info.playerInfo.LobbyRoute = buf.LobbyRoute;
            SocketManager.ins.connect();
        }, IHttpMethod.POST);
    }
    /**
     * 微信登录
     * @param callback 
     */
    private wxLoginCode(): void {
        Log.ins.log(1, '拉起微信登录')
        wx.login({
            success: (res) => {
                Log.ins.log(1, res);
                if (res.code) {
                    // SdkTool.ins.openid = res.code;
                    Log.ins.log(1, '登录成功：' + res.code);
                    this.loginGameServer(res.code);
                } else {
                    Log.ins.log(3, '登录失败！' + res.errMsg);
                }
            },
            fail: (res) => {
                Log.ins.log(3, '登录方法调用失败', res);
            }
        }
        )
    }
    /**
     * 登出
     */
    public logout(): void {
        Log.ins.log(1, "WxSdk logout");
    }

    /**
     * 退出
     */
    public exit(): void {
        Log.ins.log(1, "WxSdk exit");
    }

    /**
     * 切换账号
     */
    public switchLogin(): void {
        Log.ins.log(1, "WxSdk switchLogin");
    }

    /**
     * 数据上报
     * @param param 参数
     */
    public report(...param: any[]): void {
        Log.ins.log(1, "WxSdk report");
    }

    /**
     * 数据上报
     * @param param 参数
     */
    public pay(...param: any[]): void {
        Log.ins.log(1, "WxSdk pay");
    }

    /**
     * 播放广告
     */
    playRewardAd(callback: Function, target: any): void {
        this.callback = callback;
        this.target = target;
        ViewManager.ins.showloading();

        // 用户触发广告后，显示激励视频广告
        this.videoAd.show().catch(() => {
            // 失败重试
            this.videoAd.load()
                .then(() => this.videoAd.show())
                .catch(err => {
                    Log.ins.log(3, '激励视频 广告显示失败')
                    this.onRewardAdCallback(false);
                })
        })
    }

    createRewardAd() {
        if (!this.videoAd) {
            this.videoAd = wx.createRewardedVideoAd({
                adUnitId: "adunit-ddb0f31aaafb9780"
            })

            this.videoAd.onClose(res => {
                // 用户点击了【关闭广告】按钮
                // 小于 2.1.0 的基础库版本，res 是一个 undefined
                if (res && res.isEnded || res === undefined) {
                    // 正常播放结束，可以下发游戏奖励
                    // callback.call(target, true);
                    this.onRewardAdCallback(true);
                }
                else {
                    // 播放中途退出，不下发游戏奖励
                    // callback.call(target, false);
                    ViewManager.ins.showtips(`播放中途退出`);
                    this.onRewardAdCallback(false);
                }
            })

            this.videoAd.onError(err => {
                wx.showToast({
                    title: '广告播放失败,请稍后再试~',
                    duration: 3000,
                    mask: true,
                })
                this.onRewardAdCallback(false);
            })
        }
    }

    onRewardAdCallback(success) {
        ViewManager.ins.removeLoading();
        if (this.callback) {
            this.callback.call(this.target, success);
            if (success) {
                this.videoAd.load();
            }
            this.callback = null;
        }
    }

    /**
     * 显示banner广告
     */
    showBannerAd(show: boolean): void {
        if (show) {
            // 在适合的场景显示 Banner 广告
            this.createBannerAd();
            this.bannerAd.show();
        }
        else {
            this.bannerAd.hide();
            this.bannerAd.destroy();
            this.bannerAd = null;
            this.createBannerAd();
        }
    }

    createBannerAd() {
        if (!this.bannerAd) {
            let sysInfo = wx.getSystemInfoSync();
            // 创建 Banner 广告实例，提前初始化
            var width = 320;
            this.bannerAd = wx.createBannerAd({
                adUnitId: 'adunit-1a608b496bfca422',
                adIntervals: 30, // 自动刷新频率不能小于30秒
                style: {
                    left: sysInfo.screenWidth / 2 - width / 2,
                    top: sysInfo.screenHeight,
                    width: width
                }
            })

            this.bannerAd.onResize(res => {
                this.bannerAd.style.top = sysInfo.screenHeight - this.bannerAd.style.realHeight;
            })

            this.bannerAd.onError(err => {
                Log.ins.log(1, `bannerAd error`, err)
            })
        }
    }

    createInterstitialAd() {
        // 创建插屏广告实例，提前初始化
        if (wx.createInterstitialAd && !this.interstitialAd) {
            this.interstitialAd = wx.createInterstitialAd({
                adUnitId: 'adunit-'
            })

            this.interstitialAd.onClose(res => {
                this.interstitialAd = null;
                this.createInterstitialAd();
            })
        }
    }

    showInterstitialAd() {
        // 在适合的场景显示插屏广告
        this.createInterstitialAd();
        if (this.interstitialAd) {
            this.interstitialAd.show().catch((err) => {
                Log.ins.log(3, `interstitialAd error`, err)
            })
        }
    }

    /**
     * 显示自定义广告
     */
    showCustomAd(show, top?, left?): void {
        if (!this.customAd) {
            this.customAd = wx.createCustomAd({
                adIntervals: 30,
                adUnitId: "adunit-",
                style: {
                    fixed: true,
                    left: left,
                    top: top,
                },
            })
        }
        if (show) {
            this.customAd.show();
        }
        else {
            this.customAd.destroy();
            this.customAd = null;
        }
    }

    /**
     * 主动拉起转发
     * query key1=val1&key2=val2
     */
    shareAppMessage(title: string = "", query: any = null, shareCallback: any = null): void {
        title = title;
        // imageUrlId = imageUrlId;
        // imageUrl = imageUrl;
        var data = {
            title: title,
            // imageUrlId: imageUrlId,
            // imageUrl: imageUrl,
            query: query
        };
        wx.shareAppMessage(data);
    }
    /**
     * 获取应用热启动参数
     *
     * @returns 返回应用启动参数，类型为 any
     */
    getAppParam(): any {
        const info = wx.getEnterOptionsSync();
        SdkTool.ins.sceneAppId = info.scene;
        SdkTool.ins.query[`roomid`] = info.query.roomid;
        SdkTool.ins.query[`nickname`] = info.query.nickname;
        return info.query;
    }
    reconnect(): void {
        ViewManager.ins.showtips(`已掉线，正在重新连接...`);
        this.wxLoginCode();
    }
    public navigateToScene(): void {

    }
    public getMenuButtonBoundingClientRect(): any {
        const res = wx.getMenuButtonBoundingClientRect();
        Log.ins.log(1, `获取菜单按钮（右上角胶囊按钮）:`, res);
        const pos = (res.height + res.top + res.height) * this.getWindowInfo();
        SdkTool.ins.topmenu = pos;
    }
    private getWindowInfo(): any {
        const res = wx.getWindowInfo();
        Log.ins.log(1, `获取窗口信息:`, res);
        const screenWidth: number = view.getVisibleSize().width;
        const screenHeight: number = view.getVisibleSize().height;
        // Log.ins.log(`屏幕宽度:${screenWidth}, 高度:${screenHeight}`);
        // Log.ins.log(`高度:${res.screenHeight / screenHeight}, 宽度:${res.screenWidth / screenWidth}`);
        return (res.screenHeight / screenHeight) + 1;
    }
    public setImRankData(val): void {

    }
    public getImRankList(): void {
        ViewManager.ins.showtips(`当前平台不支持排行榜`);
    }
    public vibrateShort(): void {
        wx.vibrateShort({
            type: `heavy`,
            style: `heavy`,
            success(res) {
                Log.ins.log(1, `vibrateShort success`);
            },
            fail(res) {
                Log.ins.log(1, `vibrateShort fail`);
            },
            complete(res) {
                Log.ins.log(1, `vibrateShort complete`);
            }
        })
    }
    /**
     * 将指定内容复制到剪贴板
     *checkPrivacy cache apiName:   apiScopeNames: ["jsapi_clipboard"]
     * @param val 需要复制到剪贴板的内容
     */
    public setClipboardData(val: string): void {
        wx.setClipboardData({
            data: val,
            success(res) {
                wx.getClipboardData({
                    success(res) {
                        Log.ins.log(1, `setClipboardData success`) // data
                    }
                })
            },
            fail(res) {
                ViewManager.ins.showtips(`当前平台不支持复制功能`);
                Log.ins.log(1, `setClipboardData fail`);
            },
        })
    }
}